// <copyright file="MembershipConfig.cs" company="Clever Software">
// Copyright (c) 2013, 2014 All Right Reserved, http://www.cleversoftware.by
//
// This source is subject to the Microsoft Permissive License.
// Please see the License.txt file for more information.
// All other rights reserved.
//
// THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY 
// KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
// PARTICULAR PURPOSE.
//
// </copyright>
// <author>Clever Software</author>
// <email>info@cleversoftware.by</email>
// <date>2014-02-04</date> 
// <summary>CleverCMS source code</summary>

[assembly: WebActivatorEx.PreApplicationStartMethod(typeof(CleverCMS.Web.App_Start.MembershipConfig), "Start")]
[assembly: WebActivatorEx.PostApplicationStartMethod(typeof(CleverCMS.Web.App_Start.MembershipConfig), "Initialize")]
namespace CleverCMS.Web.App_Start
{
    using System;
    using System.Linq;
    using System.Web.Security;
    using System.Collections.Specialized;
    using System.Configuration;
    using System.Data.Entity;
    using System.Data.Entity.Infrastructure;
 
    using WebMatrix.WebData;

    using CleverCMS.Core.Services;
    using CleverCMS.Cms.Data;
    using CleverCMS.Blog.Data;

	public static class MembershipConfig
	{
		public static readonly string EnableSimpleMembershipKey = "enableSimpleMembership";

		public static bool SimpleMembershipEnabled
		{
			get { return IsSimpleMembershipEnabled(); }
		}
		
		public static void Initialize()
		{           
            try
            {
                using (var context = new CmsDataContext())
                using (var blogcontext = new BlogDataContext())
                {
                    if (!context.Database.Exists())
                    {
                        //TODO: Find the way of dynamic database parts creation depending on modules.
    
                        Database.SetInitializer<CmsDataContext>(new CmsContextInit());
                        ((IObjectContextAdapter)context).ObjectContext.AcceptAllChanges();

                        Database.SetInitializer<BlogDataContext>(new BlogContextInit());
                        ((IObjectContextAdapter)blogcontext).ObjectContext.AcceptAllChanges();
                        //-----------------------------------------------------------------------//

                        SearchService.AddUpdateLuceneIndex(context.CmsPages.ToList());
                        SearchService.AddUpdateLuceneIndex(blogcontext.BlogEntries.ToList());

                        WebSecurity.InitializeDatabaseConnection(connectionStringName: "DataContext",  userTableName: "UserProfile", userIdColumn: "Id", userNameColumn: "Login", autoCreateTables: true);

                        if (!Roles.RoleExists("Admin"))
                            Roles.CreateRole("Admin");

                        if (!Roles.RoleExists("User"))
                            Roles.CreateRole("User");

                        if (!Roles.RoleExists("ContentManager"))
                            Roles.CreateRole("ContentManager");

                        WebSecurity.CreateUserAndAccount("Admin", "123456",
                            new
                            {
                                DisplayName = "Admin",
                                CreatedAt = DateTime.Now,
                                Email = "sampledata@gmail.com"
                            });

                        if (!Roles.GetRolesForUser("Admin").Contains("Admin"))
                            Roles.AddUsersToRoles(new[] { "Admin" }, new[] { "Admin" });

                        WebSecurity.CreateUserAndAccount("User", "123456",
                            new
                            {
                                DisplayName = "Test User",
                                CreatedAt = DateTime.Now,
                                Email = "testuser@gmail.com"
                            });

                        if (!Roles.GetRolesForUser("User").Contains("User"))
                            Roles.AddUsersToRoles(new[] { "User" }, new[] { "User" });
                    }
                    else
                    {
                        //Database.SetInitializer<DataContext>(new ContextInitWithoutDrop());
                        //((IObjectContextAdapter)context).ObjectContext.AcceptAllChanges();

                        //SearchService.AddUpdateLuceneIndex(context.CmsPages.ToList());
                        //SearchService.AddUpdateLuceneIndex(context.BlogEntries.ToList());

                        WebSecurity.InitializeDatabaseConnection(connectionStringName: "DataContext", userTableName: "UserProfile", userIdColumn: "Id", userNameColumn: "Login", autoCreateTables: false);

                        //if (!Roles.RoleExists("Admin"))
                        //    Roles.CreateRole("Admin");

                        //if (!Roles.RoleExists("User"))
                        //    Roles.CreateRole("User");

                        //if (!WebSecurity.UserExists("Admin"))
                        //    WebSecurity.CreateUserAndAccount("Admin", "123456",
                        //    new
                        //    {
                        //        DisplayName = "Admin",
                        //        CreatedAt = DateTime.Now,
                        //        Email = "sampledata@gmail.com"
                        //    });

                        //if (!Roles.GetRolesForUser("Admin").Contains("Admin"))
                        //    Roles.AddUsersToRoles(new[] { "Admin" }, new[] { "Admin" });
                    }
                }

            }
            catch (Exception ex)
            {
                throw new InvalidOperationException("The ASP.NET Simple Membership database could not be initialized. For more information, please see http://go.microsoft.com/fwlink/?LinkId=256588", ex);
            }
		}

		public static void Start()
		{
			if (SimpleMembershipEnabled)
			{
				MembershipProvider provider = Membership.Providers["AspNetSqlMembershipProvider"];
				if (provider != null)
				{
					MembershipProvider currentDefault = provider;
					SimpleMembershipProvider provider2 = CreateDefaultSimpleMembershipProvider("AspNetSqlMembershipProvider", currentDefault);
					Membership.Providers.Remove("AspNetSqlMembershipProvider");
					Membership.Providers.Add(provider2);
				}
				Roles.Enabled = true;
				RoleProvider provider3 = Roles.Providers["AspNetSqlRoleProvider"];
				if (provider3 != null)
				{
					RoleProvider provider6 = provider3;
					SimpleRoleProvider provider4 = CreateDefaultSimpleRoleProvider("AspNetSqlRoleProvider", provider6);
					Roles.Providers.Remove("AspNetSqlRoleProvider");
					Roles.Providers.Add(provider4);
				}
			}
		}

		#region : Private Methods :

		private static bool IsSimpleMembershipEnabled()
		{
			bool flag;
			string str = ConfigurationManager.AppSettings[EnableSimpleMembershipKey];
			if (!string.IsNullOrEmpty(str) && bool.TryParse(str, out flag))
			{
				return flag;
			}
			return true;
		}

		private static SimpleMembershipProvider CreateDefaultSimpleMembershipProvider(string name, MembershipProvider currentDefault)
		{
			MembershipProvider previousProvider = currentDefault;
			SimpleMembershipProvider provider = new SimpleMembershipProvider(previousProvider);
			NameValueCollection config = new NameValueCollection();
			provider.Initialize(name, config);
			return provider;
		}

		private static SimpleRoleProvider CreateDefaultSimpleRoleProvider(string name, RoleProvider currentDefault)
		{
			RoleProvider previousProvider = currentDefault;
			SimpleRoleProvider provider = new SimpleRoleProvider(previousProvider);
			NameValueCollection config = new NameValueCollection();
			provider.Initialize(name, config);
			return provider;
		}

		#endregion

	}
}